package com.mayikt.generator;

import com.mayikt.utils.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.UUID;

/**
 * @Classname TokenGenerator
 * @Description SpringBoot SpringCloud 构建微服务电商平台。
 * @Created by CHEN JIN LONG
 * @Date 2019/1/25 11:25
 * @Version 1.0
 */
@Component
@Slf4j
public class TokenGenerator {

    @Autowired
    private RedisUtils redisUtils;

    /**
     * 生成token
     *
     * @param keyPrefix
     * @param redisValue
     * @return
     */
    public String createToke(String keyPrefix, String redisValue) {
        return createToke(keyPrefix, redisValue, 0l);
    }

    /**
     * 生成token
     *
     * @param keyPrefix
     * @param redisValue
     * @param time
     * @return
     */
    public String createToke(String keyPrefix, String redisValue, Long time) {
        if (StringUtils.isEmpty(redisValue))
            new Exception("redisValue is Not null");
        String token = keyPrefix + "_" + UUID.randomUUID().toString().replace("-", "");
        redisUtils.set(token, redisValue, time);
        return token;

    }

    /**
     * 从redis中获取token value值
     *
     * @param token
     * @return
     */
    public String getToken(String token) {
        if (StringUtils.isEmpty(token))
            new Exception("token is Not null");
        return redisUtils.get(token);
    }

    /**
     * 移除token
     *
     * @param token
     */
    public void removeToken(String token) {
        if (StringUtils.isEmpty(token))
            new Exception("token is Not null");
        redisUtils.del(token);
    }
}
